package org.example.Polls;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class VoteOnPollActivity extends Activity implements OnCheckedChangeListener, OnClickListener {
	private static final String TAG = "VoteOnPollActivity";
	public static final String POLL_ID_EXTRA = "uVote.VoteOnPollActivity.pollId";
	
	private Poll poll;
	private TextView pollTitle;
	private TextView pollAdmin;
	private Button voteButton;
	private RadioGroup radioGroup;
	
	private List<RadioButton> radioButtons = new ArrayList<RadioButton>();
	private Map<RadioButton, Long> radioButtonMap = new HashMap<RadioButton, Long>();
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vote_on_poll);
        
        Bundle extras = getIntent().getExtras();
        Log.d(TAG, "extras: " + extras);
        Long pollId = extras.getLong(VoteOnPollActivity.POLL_ID_EXTRA);
        Log.d(TAG, "pollID: " + pollId);
        try {
    		poll = PollHelper.getPoll(pollId);
        } catch (Exception e) {
        	this.finish();
        	e.printStackTrace();
        }
        Log.d(TAG, poll.getTitle());
        Log.d(TAG, poll.getAdministrator().getEmail());
        
        pollTitle = (TextView) findViewById(R.id.vote_on_poll_poll_title_id);
        pollAdmin = (TextView) findViewById(R.id.vote_on_poll_poll_admin_id);
        radioGroup = (RadioGroup) findViewById(R.id.vote_on_poll_radio_group);
        
        PollItem pollItemSelected = null;
        RequestContext ctxt = RequestContext.getContext();
        for(PollParticipant pollParticipant : poll.getParticipants()) {
        	if(ctxt.getUsername().equals(pollParticipant.getEmail())) {
        		Log.d(TAG, ctxt.getUsername()+" is a participant in poll \""+poll.getTitle()+"\"");
        		pollItemSelected = pollParticipant.getVote();
        		if (pollItemSelected != null) {
        			Log.d(TAG, ctxt.getUsername()+" previously voted for item \""+pollItemSelected.getText()+"\"");
        		}
        	}
        }
        
        // dynamically add list items from specific poll's item list.
        List<PollItem> pollItemList = new ArrayList(poll.getItems());
        Collections.sort(pollItemList, new Comparator<PollItem>(){
			public int compare(PollItem lhs, PollItem rhs) {
				return lhs.getText().toLowerCase().compareTo(rhs.getText().toLowerCase());
			}
        });
        for(PollItem pollItem : pollItemList) {
        	RadioButton radioButton = new RadioButton(this);
        	radioButton.setTag(pollItem.getId());
        	radioButton.setText(pollItem.getText());
        	radioButton.setEnabled(true);
        	radioButton.setOnCheckedChangeListener(this);
        	if(pollItemSelected != null) {
        		if(pollItem.getId().equals(pollItemSelected.getId())) {
        			Log.d(TAG, "Checking the radiobutton from before");
        			radioButton.setChecked(true);
        		}
        	}
        	radioButtons.add(radioButton);
        	radioButtonMap.put(radioButton, pollItem.getId());
        	radioGroup.addView(radioButton, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        }
        
        voteButton = (Button) findViewById(R.id.vote_on_poll_button_id);
        voteButton.setOnClickListener(this);
        
        pollTitle.setText(poll.getTitle());
        pollAdmin.setText(poll.getAdministrator().getFirstName() + " " + poll.getAdministrator().getLastName());
        
        // TODO: if poll is dynamic, show button that allows user to add additional items to the options available to choose from.
    }
    
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) processRadioButtonClick(buttonView);
	}
	
	private void processRadioButtonClick(CompoundButton buttonView){
	    for (RadioButton button : radioButtons){
	        if (button != buttonView ) button.setChecked(false);
	    }
	}

	public void onClick(View v) {
		Log.d(TAG, "Vote button clicked.");
		for (RadioButton radioButton : radioButtons) {
			if (!radioButton.isChecked())
				continue;
			
			Long pollItemId = (Long)radioButton.getTag();
			Log.i(TAG, "User is voting for pollItemId="+pollItemId+", \""+radioButton.getText()+"\"");
			PollService pollService = DefaultServiceFactory.getInstance().createPollService();
			RequestContext ctxt = RequestContext.getContext();
			try {
				pollService.vote(ctxt, poll.getId(), pollItemId);
				Log.i(TAG, "Vote successful, forcing cache refresh");
				PollHelper.getPoll(poll.getId(), true);
				setResult(RESULT_OK);
				this.finish();
			} catch (Exception e) {
				Log.d(TAG, "caught exception creating user", e);
				e.printStackTrace();
        		AlertDialog.Builder builder = new AlertDialog.Builder(this);
        		builder.setMessage(e.toString())
        		       .setCancelable(false)
        		       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        		    	   public void onClick(DialogInterface dialog, int id) {
        		    		   dialog.dismiss();
        		    	   }
        		       });
        		AlertDialog dialog = builder.create();
        		dialog.show();
			}
		}
	}

}
